package com.cogent.dynamicform.form.impl;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import com.cogent.common.util.MapUtil;
import com.cogent.common.util.StringUtil;
import com.cogent.dao.BussinessInstance;
import com.cogent.dao.BussinessQueryHelper;
import com.cogent.dao.facade.BussinessDaoFacade;
import com.cogent.dynamicform.domain.BaseFormColumnDomain;
import com.cogent.dynamicform.domain.FormColumnDomain;
import com.cogent.dynamicform.form.AbstractDynamicForm;

public class QuerySelectTextDynamicFormImpl extends AbstractDynamicForm {
	public String genQueryField(BaseFormColumnDomain formColumnDomain, HashMap formMap) {
		return "";
	}
	
	public String genInputField(FormColumnDomain formColumnDomain, HashMap formMap) {
		if(formColumnDomain.getViewmodel() > 0)
			return getShowValue(formColumnDomain, formMap) + "&nbsp;";
		StringBuffer str = new StringBuffer();
		String[] curname = formColumnDomain.getName().split("~");
		String curvalue = "";
		if(MapUtil.isEmpty(formMap, curname[0]))
			curvalue = getShowValue(formColumnDomain, formMap);
		str.append("<input type=\"hidden\" id=\"").append(curname[0]).append("\" name=\"").append(curname[0]).append("\"/>");
		str.append("<input type=\"text\" id=\"").append(curname[1]).append("\" name=\"")
			.append(curname[1]);
		String className = "middle_text";
		if(!StringUtil.isEmpty(formColumnDomain.getShowclass()))
			className = formColumnDomain.getShowclass();
		str.append("\" class=\"").append(className).append("\" maxlength=\"120\"").append(" value=\"")
			.append(curvalue).append("\"");
		if(!StringUtil.isEmpty(formColumnDomain.getJs()))
			str.append(formColumnDomain.getJs());
		if(!StringUtil.isEmpty(formColumnDomain.getShowcontrol()))
			str.append(formColumnDomain.getShowcontrol());
		str.append("/>");
		if(formColumnDomain.isIsrequired())
			str.append("<span class=\"txt_red\">&nbsp;*</span>");
		if(!StringUtil.isEmpty(formColumnDomain.getNotemsg()))
			str.append(formColumnDomain.getNotemsg());
		if(!StringUtil.isEmpty(formColumnDomain.getPopfullup()))
			str.append(formColumnDomain.getPopfullup());
		
		return str.toString();
	}
	
	@SuppressWarnings("unchecked")
	public String getShowValue(BaseFormColumnDomain formColumnDomain, HashMap formMap) {
		if(formColumnDomain.getShowtype() == 1)
			return "&nbsp;";
		String[] curname = formColumnDomain.getName().split("~");
		String curvalue = curname[0];
		BussinessInstance bussinessInstance = new BussinessInstance();
		BussinessDaoFacade bussinessFacade = bussinessInstance.getBussinessFacade();
		String sql = formColumnDomain.getTypecode(); 
		List list = BussinessQueryHelper.query(sql);
		Iterator it = list.iterator();
		while(it.hasNext()) {
			HashMap dataMap = (HashMap)it.next();
			if(curvalue.equals(MapUtil.getStringValue(dataMap, "enumvalue")))
				return MapUtil.getStringValue(dataMap, "enumoption");
		}
		
		return "&nbsp;";
	}
}
